<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
      label-width="120px" label-position="top">
      <el-row>
        <el-col :span="9">
          <el-form-item prop="name" :label="$t('education.name')">
            <el-input v-model="dataForm.name" :placeholder="$t('education.name')"></el-input>
          </el-form-item>
          <el-form-item prop="principal" label="教育局责任人姓名">
            <el-input v-model="dataForm.principal" placeholder="教育局责任人姓名"></el-input>
          </el-form-item>
          <el-form-item prop="area" label="教育局所属行政区划">
            <el-row>
              <!-- <el-cascader v-model="value" :options="regionList" @change="handleChange"></el-cascader> -->
              <el-col :span="12">
                <!-- <el-select v-model="value" placeholder="请选择">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select> -->
                <el-input v-model="dataForm.divisionProvince" placeholder="行政区划-省"></el-input>
              </el-col>
              <el-col :span="11" :offset="1">
                <!-- <el-select v-model="value" placeholder="请选择">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select> -->
                <el-input v-model="dataForm.divisionCity" placeholder="行政区划-市"></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <!-- <el-form-item prop="name" label="运维责任人">
            <el-select v-model="value" placeholder="请选择">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item> -->
        </el-col>
        <el-col :span="14" :offset="1">
          <!-- <el-form-item prop="email" label="管理账户名">
            <el-input v-model="dataForm.email" :placeholder="$t('user.email')"></el-input>
          </el-form-item> -->
          <el-form-item prop="principalPhone" label="教育局责任人手机号">
            <el-input v-model="dataForm.principalPhone" :placeholder="$t('user.mobile')"></el-input>
          </el-form-item>
          <el-form-item prop="area" label="教育局详细地址">
            <el-row>
              <el-col :span="7">
                <!-- <el-select v-model="value" placeholder="请选择">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select> -->
                <el-input v-model="dataForm.addrProvince" placeholder="地址-省"></el-input>
              </el-col>
              <el-col :span="8" :offset="1">
                <!-- <el-select v-model="value" placeholder="请选择">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select> -->
                <el-input v-model="dataForm.addrCounty" placeholder="地址-市"></el-input>
              </el-col>
              <el-col :span="7" :offset="1">
                <!-- <el-select v-model="value" placeholder="请选择">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select> -->
                <el-input v-model="dataForm.addrCity" placeholder="地址-区县"></el-input>
              </el-col>
            </el-row>
            <el-input v-model="dataForm.detailAddr" placeholder="详细地址"></el-input>
          </el-form-item>
          <el-form-item prop="postIdList" label="合同文件上传" class="role-list">
            <el-upload class="upload-demo" drag action="https://jsonplaceholder.typicode.com/posts/" multiple>
              <div class="el-upload__tip">支持上传JPG、JPEG 、PNG格式图片（不限张）</div>
              <div class="el-upload__tip">支持PDF文件上传（不限张）</div>
              <div class="el-upload__text">单个图片/文件最大不超过30MB</div>
              <el-button type="primary" icon="el-icon-plus">上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>


    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { isEmail, isMobile } from "@/utils/utils";
import { IObject } from "@/types/interface";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const regionList = ref();
const roleList = ref<any[]>([]);
const postList = ref<any[]>([]);
const dataFormRef = ref();

const dataForm = reactive({
  id: "",
  name: "",
  principal: "",
  principalPhone: "",
  // deptName: "",
  password: "",
  // confirmPassword: "",
  // realName: "",
  // gender: 0,
  // email: "",
  // principalPhone: "",
  // roleIdList: [] as IObject[],
  // postIdList: [] as IObject[],
  // status: 1,
  divisionProvince: "",
  divisionCity: "",
  detailAddr: "",
  addrProvince: "",
  addrCity: "",
  addrCounty: ""
});


const validatePassword = (rule: any, value: string, callback: (e?: Error) => any): any => {
  if (!dataForm.id && !/\S/.test(value)) {
    return callback(new Error(t("validate.required")));
  }
  callback();
};
const validateConfirmPassword = (rule: any, value: string, callback: (e?: Error) => any): any => {
  if (!dataForm.id && !/\S/.test(value)) {
    return callback(new Error(t("validate.required")));
  }
  if (dataForm.password !== value) {
    return callback(new Error(t("user.validate.confirmPassword")));
  }
  callback();
};
const validateEmail = (rule: any, value: string, callback: (e?: Error) => any): any => {
  if (value && !isEmail(value)) {
    return callback(new Error(t("validate.format", { attr: t("user.email") })));
  }
  callback();
};
const validateMobile = (rule: any, value: string, callback: (e?: Error) => any): any => {
  if (value && !isMobile(value)) {
    return callback(new Error(t("validate.format", { attr: t("user.mobile") })));
  }
  callback();
};
const rules = ref({
  username: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  deptName: [{ required: true, message: t("validate.required"), trigger: "change" }],
  password: [{ validator: validatePassword, trigger: "blur" }],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: "blur" }],
  realName: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  email: [{ validator: validateEmail, trigger: "blur" }],
  mobile: [{ validator: validateMobile, trigger: "blur" }]
});

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  Promise.all([getRoleList(), getPostList(), getRegionList()]).then(() => {
    if (id) {
      getInfo(id);
    }
  });
};

// 获取角色列表
const getRoleList = () => {
  return baseService.get("/sys/role/list").then((res) => {
    roleList.value = res.data;
  });
};

// 获取岗位列表
const getPostList = () => {
  return baseService.get("/sys/post/list").then((res) => {
    postList.value = res.data;
  });
};

// 获取区域列表
const getRegionList = () => {
  return baseService.get("/sys/region/region", {threeLevel: false}).then((res) => {
    regionList.value = res.data;
  });
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get(`/sys/user/${id}`).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    baseService.post
    (!dataForm.id ? '/edu/tenant/add' : '/edu/tenant/mod', {
      ...dataForm,
    }).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>

<style lang="less" scoped>
.mod-sys__user {
  .role-list {
    .el-select {
      width: 100%;
    }
  }
}
</style>
